package icom.acm.demo.serverpush.dwr;

import icom.acm.demo.serverpush.Message;
import icom.acm.demo.serverpush.User;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;

import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;


/**
 * DWR ServerPushDemo
 * @author shench
 *
 */
public class PushDWRManager {
	private static LinkedList<Message> messages = new LinkedList<Message>();
	private ScriptSession session;
	
    
	public PushDWRManager(){}
	
	public String getTest(){		
		System.out.println("Hello, DWR!");
		return "Hello, DWR!";
	}
	
	public String send(String msg){
		System.out.println("send:"+msg);
		
		
		
		WebContext wctx = WebContextFactory.get();
        String currentPage = wctx.getCurrentPage();
                
        Message m = new Message();
        User user = (User) wctx.getSession().getAttribute("user");
        m.setUser(user);
		m.setContent(msg);
		messages.addFirst(m);
        
        ScriptBuffer script = new ScriptBuffer();
        script.appendScript("receive(")
              .appendData(m)
              .appendScript(");");

        // Loop over all the users on the current page
        Collection pages = wctx.getScriptSessionsByPage(currentPage);
        for (Iterator it = pages.iterator(); it.hasNext();)
        {
            ScriptSession otherSession = (ScriptSession) it.next();
            otherSession.addScript(script);
        }
		
		return msg;
	}
}
